import allure

from tools.handle_replace_mark_data import replace_mark_data_by_re
from tools.global_data import GlobalData
from tools.my_sql import MyMySQL
from settings import sql_settings
from loguru import logger


@allure.step("===数据库断言===")
def check_db(check_db_str):
    """
    数据库断言
    :param check_db_str: excel中check_db字段的值，string类型
    :return: None
    """
    logger.info("===断言数据库===")
    # 替换check_db字段的占位符
    check_db_str = replace_mark_data_by_re(check_db_str)
    check_db_list = eval(check_db_str)
    # 连接数据库
    mmsql = MyMySQL(**sql_settings)
    for one_check_db_dict in check_db_list:
        # 判断type类型
        if one_check_db_dict.get("type") == "count":
            logger.info("type类型为count,执行获取条数sql语句")
            result = mmsql.get_count_from_database(one_check_db_dict.get("sql"))
            logger.info(f"sql语句结果={result}")
        else:
            result = ""
            logger.info("暂不支持此类型")
        try:
            logger.info(f"期望结果={one_check_db_dict.get('expected')}")
            assert result == one_check_db_dict.get("expected")
        except:
            logger.exception("断言失败")
            raise
        else:
            logger.info("断言成功，实际结果和期望结果相同")
    mmsql.close()


if __name__ == '__main__':
    setattr(GlobalData, "new_phone", "15178172062")
    sss = '[{"type":"count","sql": "SELECT * FROM tz_user WHERE user_mobile=#new_phone#","expected": 2}]'
    check_db(sss)
